/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package communicator;

import debug.DebugFrame;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import communicator.message.*;
import base.*;
import java.net.ConnectException;

/**
 *
 * @author Mr.Black
 */
public class Sender extends Thread {

    private final static int PORT = 9999;
    private Socket clientSocket;        
    private ObjectOutputStream oos;
    private SynchronousQueue listMsg;

    public Sender(SynchronousQueue msgQueue) {
        DebugFrame.receivMsg("Sender is running..." + "\n");
        listMsg = msgQueue;
    }

    @Override
    public void run() {
        while (true) {            
            Message msg = (Message) listMsg.dequeue();
            sendMessage(msg);
        }
    }

    public void sendMessage(Message msg) {
        try {
            DebugFrame.receivMsg("Thong tin cua message:" + "\n");
            DebugFrame.receivMsg("\tTo Host : " + msg.getDestinationComputer() + "\n");
            int pos = checkHost2Connect(msg.getDestinationComputer());
            Utilities.CPPrint("POST: " + pos);
            if (pos == -1) {
               
                    DebugFrame.receivMsg("\tMessage co dich la host moi. Tao ket noi!" + "\n");
                    clientSocket = new Socket(msg.getDestinationComputer(), PORT);
                    new ProcessClient(clientSocket).start();
                    oos = new ObjectOutputStream(clientSocket.getOutputStream());
                    Receiver.listClientOOS.add(oos);
                    Receiver.listHostAddress.add(clientSocket.getInetAddress().getHostAddress());                
            } else {
                DebugFrame.receivMsg("\tMessage co dich la host da co. Send vao socket tuong ung! " + ((String) Receiver.listHostAddress.elementAt(pos)) + "\n");
                oos = (ObjectOutputStream) Receiver.listClientOOS.elementAt(pos);
            }            
            oos.writeObject(msg);
        } catch (UnknownHostException ex) {
            DebugFrame.receivMsg("Khong the ket noi toi may " + msg.getDestinationComputer() + ": " + ex.toString()  + "\n");
        } catch (ConnectException conEx){
            DebugFrame.receivMsg("Khong the ket noi toi may " + msg.getDestinationComputer() + ": " + conEx.toString() + "\n");
        }
        catch (Exception ex) {
            DebugFrame.receivMsg("Khong the ket noi toi may " + msg.getDestinationComputer() + ": " + ex.toString() + "\n");
            ex.getStackTrace();
        }
    }

    public static int checkHost2Connect(String host) {        
        for (int i=0; i<Receiver.listHostAddress.size(); i++) {
            if (host.equals((String) Receiver.listHostAddress.elementAt(i)))
                return i;
        }
        return -1;
    }
}
